/*
 * Copyright (c) 2013. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.jspx.jubb;

import com.jspx.boot.EnvFactory;
import com.jspx.boot.environment.Environment;
import com.jspx.boot.environment.EnvironmentTemplate;
import com.jspx.json.JSONObject;
import com.jspx.security.asymmetric.AsyEncrypt;
import com.jspx.security.symmetry.AbstractEncrypt;
import com.jspx.security.symmetry.Encrypt;
import com.jspx.security.symmetry.impl.SM4Encrypt;
import com.jspx.security.utils.EncryptUtil;
import com.jspx.util.StringMap;
import com.jspx.utils.*;
import jspx.user.payment.env.PaymentEnv;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: yuan
 * Date: 13-8-25
 * Time: 下午10:07
 */
public class IntegralFilter extends HTMLFilter {

    private float integral = 0;
    private String integralTip = "【此部分为隐藏内容,支付${integral}积分后可看,<button class=\"paymentButton\" pay=\"${payData}\" integral=\"${integral}\" sign=\"${sign}\" signType=\"${signType}\">支付</button>】";

    private Map<Integer, Integer> payMap = new HashMap<Integer, Integer>();
    private Map<String, Object> valueMap = new HashMap<String, Object>();

    public IntegralFilter(String s) {
        super(s);
    }

    public IntegralFilter() {

    }

    public Map<Integer, Integer> getPayMap() {
        return payMap;
    }

    public void setPayMap(Map<Integer, Integer> payMap) {
        this.payMap = payMap;
    }

    public void setValueMap(Map<String, Object> valueMap) {
        this.valueMap = valueMap;
    }

    public float getIntegral() {
        return integral;
    }

    public void setIntegral(float integral) {
        this.integral = integral;
    }

    public String getIntegralTip() {
        return integralTip;
    }

    public void setIntegralTip(String integralTip) {
        this.integralTip = integralTip;
    }

    public String convertString() {
        return hideConverter();
    }

    public String hideConverter() {

        boolean isGuest = ObjectUtil.toBoolean(valueMap.get("isGuest"));
        AsyEncrypt encrypt = EnvFactory.getAsymmetricEncrypt();
        final Map<Integer, Integer> integralMap = new HashMap<Integer, Integer>();
        Pattern pattern = Pattern.compile("(\\[integral=([0-9]*)\\])(.+?)(\\[\\/integral\\])", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(s);
        StringBuffer stringbuffer = new StringBuffer();
        valueMap.put(PaymentEnv.KEY_currency,"integral");
        //不能删除,后边还要用的
        String payPrivateKey = (String)valueMap.get(Environment.payPrivateKey);
        int i = 0;
        for (boolean flag = matcher.find(); flag; flag = matcher.find()) {

            valueMap.remove("sign");
            valueMap.remove("payData");
            String lan = matcher.group(2);
            int payValue = StringUtil.toInt(lan);
            i++;
            integralMap.put(i, payValue);
            valueMap.put(PaymentEnv.KEY_integral, payValue);
            valueMap.put("sort", i);
            if (!isGuest && StringUtil.isNumber(lan) && payMap.containsKey(i) && payMap.get(i) >= integralMap.get(i)) {
                matcher.appendReplacement(stringbuffer, matcher.group(3));
            } else {
                JSONObject json = new JSONObject();
                json.put("tid",valueMap.get("tid"));
                json.put("paySign",valueMap.get("paySign")); //支付标识
                json.put("sort",valueMap.get("sort"));
                json.put(PaymentEnv.KEY_currency,valueMap.get(PaymentEnv.KEY_currency));

                valueMap.put(PaymentEnv.KEY_optional,json.toString());


                StringMap payMap = new StringMap();
                payMap.setKeySplit(StringUtil.EQUAL);
                payMap.setLineSplit(StringUtil.CRLF);
                payMap.putAll((Map) valueMap);
                //排序统一标准
                payMap.sortByKey(false);

                try {

                    if (isGuest) {
                        valueMap.put("payData", "");
                        valueMap.put("sign", "");
                        matcher.appendReplacement(stringbuffer, integralTip);
                    } else {
                        String payData = EncryptUtil.byteToHex(ZipUtil.zip(payMap.toString().getBytes(Environment.defaultEncode)));
                        byte[] signByte = encrypt.sign(payData.getBytes(Environment.defaultEncode), EncryptUtil.hexToByte(payPrivateKey));
                        valueMap.put("payData", payData);
                        valueMap.put("sign",EncryptUtil.byteToHex(signByte));
                        String txt = EnvFactory.getPlaceholder().processTemplate(valueMap, integralTip);
                        matcher.appendReplacement(stringbuffer, txt);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    matcher.appendReplacement(stringbuffer, "integralTip 提示配置错误");
                }
            }
        }
        matcher.appendTail(stringbuffer);

        return stringbuffer.toString();
    }
}